package user

import (
	"context"
	"database/sql"
	"fmt"
	"github.com/zeromicro/go-zero/core/stores/sqlc"
	"go-admin/base/dao"

	"go-admin/base/internal/svc"
	"go-admin/base/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type SaveLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewSaveLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SaveLogic {
	return &SaveLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *SaveLogic) Save(req *types.UserSaveReqDTO) (resp *types.UserBooleanRespDTOS, err error) {

	_, err = l.svcCtx.UserModel.FindOneByUserNum(l.ctx, req.UserNum)
	if err != nil {
		if err != sqlc.ErrNotFound {
			fmt.Errorf(err.Error())
			return nil, err
		}
	} else {
		return &types.UserBooleanRespDTOS{
			Data: false,
			Result: types.Result{
				Code:    444,
				Message: "账号已存在！" + req.UserNum,
			},
		}, nil
	}

	_, err = l.svcCtx.UserModel.Insert(l.ctx, &dao.User{
		UserName: sql.NullString{
			String: req.UserName,
			Valid:  true,
		},
		UserNum: sql.NullString{
			String: req.UserNum,
			Valid:  true,
		},
		NickName: sql.NullString{
			String: req.NickName,
			Valid:  true,
		},
		Password: sql.NullString{
			String: req.Password,
			Valid:  true,
		},
	})
	if err != nil {
		fmt.Errorf(err.Error())
		return nil, err
	}
	return &types.UserBooleanRespDTOS{
		Data: true,
		Result: types.Result{
			Code: 200,
		},
	}, nil
}
